package security.security;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.StringUtils;
import security.security.login.SecurityUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    private static final String SECRET = "ThisIsASecret";
    private static final String HEADER = "Authorization";
    private static final String HEADER_PREFIX = "Bearer ";
    private static final String TOKEN_USERNAME = "username";
    private static final String TOKEN_ROLES = "roles";

    public static void generateToken(SecurityUser user) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
        map.put(TOKEN_USERNAME, user.getUsername());
        StringBuffer roles = new StringBuffer();
        for(GrantedAuthority authority : user.getAuthorities()){
            roles.append(authority.getAuthority())
            .append(",");
        }
        if(roles.length() > 1){
            map.put(TOKEN_ROLES, roles.deleteCharAt(roles.length()-1));
        }

        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 3600_000_000L))// 1000 hour
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        Utils.getResponse().setHeader(HEADER, HEADER_PREFIX + jwt);
    }

    public static Map<String, Object> validateToken() {
        return validateToken(getToken());
    }

    public static Map<String, Object> validateToken(String token) {
        try {
            // parse the token.
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(HEADER_PREFIX,""))
                    .getBody();
            logger.debug("jwt body: {}", body);
            return  body;
        }catch (Exception e){

            throw new IllegalStateException("Invalid Token. "+e.getMessage());
        }
    }
    public static String getCurrentUsername() {
        Map<String, Object> body = validateToken();
        return String.valueOf(body.get(TOKEN_USERNAME));
    }
    public static String getCurrentUserRoles() {// user,admin
        Map<String, Object> body = validateToken();
        String roles = String.valueOf(body.get(TOKEN_ROLES));
        if(StringUtils.isEmpty(roles)){
            return "";
        }
        return roles;
    }
    public static String getUsernameByToken(String token) {// 使用url参数时
        Map<String, Object> body = validateToken(token);
        return String.valueOf(body.get(TOKEN_USERNAME));
    }

    public static String getToken(){
        String header = Utils.getRequest().getHeader(HEADER);
        if(StringUtils.isEmpty(header)){
            return "";
        }
        return header.replace(HEADER_PREFIX,"");
    }

    public static void main(String[] args) {
//        System.out.println(generateToken("18611111111"));
        logger.debug("{}",validateToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NDI0NzgxNjksInVzZXJuYW1lIjoiMTg2MTExMTExMTEifQ.dRamjcY_MV-ypJUVSM1jQI00mHEkwoLVjkocx48he1P6aA4MobaDQlmSn5W-1EDyzaaSVlmixQBg5N-NHUYeEg"));
    }
}
